package com.java.jwt.exception;

import com.baomidou.mybatisplus.extension.api.R;
import com.java.jwt.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常处理器
 */
@RestControllerAdvice
@Slf4j
public class RRExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public CommonResult handleRRException(RRException e) {
        log.error(getMessage(e));
        return CommonResult.failed(e.getMessage());
//		return R.error().message(e.getMessage()).code(e.getCode());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult handleException(Exception e) {
        log.error(getMessage(e));
        return CommonResult.failed(e.getMessage());
    }

    public static String getMessage(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

}
